
/*
 * @Author: lxh lxhcnasiaworld@gmail.com
 * @Date: 2024-06-08 15:19:47
 * @LastEditors: lxh lxhcnasiaworld@gmail.com
 * @LastEditTime: 2024-06-16 15:47:26
 * @FilePath: /example/src/main.rs
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
mod handler;
mod model;
mod route;
mod schema;

use std::sync::Arc;
use axum::{http::{header::{ACCEPT, AUTHORIZATION, CONTENT_TYPE}, HeaderValue, Method}, response::IntoResponse, routing::get, Json, Router};
use dotenv::dotenv;
use sqlx::mysql::{MySqlPool, MySqlPoolOptions};
use tower_http::cors::CorsLayer;
use route::create_router;



pub struct AppState {
  db: MySqlPool,
}

#[tokio::main]
async fn main() {
    // 数据库连接
    dotenv().ok();
    let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let pool_options =  MySqlPoolOptions::new().max_connections(5);
    let pool = match pool_options.connect(&database_url).await
    {
        Ok(pool) => {
          println!("✅连接数据库成功!");
          pool
        }
        Err(err)=> {
          println!("🔥 Failed to connect to the database: {:?}", err);
            std::process::exit(1);
        }
          
    };

    // 跨域设置
    let cors = CorsLayer::new()
    .allow_origin("http://localhost:3000".parse::<HeaderValue>().unwrap())
    .allow_methods([Method::GET, Method::POST, Method::PATCH, Method::DELETE])
    .allow_credentials(true)
    .allow_headers([AUTHORIZATION, ACCEPT, CONTENT_TYPE]);

    let app = create_router(Arc::new(AppState { db: pool.clone() })).layer(cors);

    println!("🚀 服务器已启动");
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8000").await.unwrap();
    axum::serve(listener, app).await.unwrap()
}

